package com.example.androidkt.sixth

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.work.BackoffPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.example.androidkt.databinding.ActivityWorkManagerBinding
import java.util.concurrent.TimeUnit
import kotlin.math.log

class WorkManagerActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val TAG = this.javaClass.simpleName

        val binding = ActivityWorkManagerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnDo.setOnClickListener {
            Log.i(TAG, "点击按钮")
            val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
                .setInitialDelay(3, TimeUnit.MINUTES)//延迟三秒
                .addTag("qaq")//添加标签，方便撤销
                .setBackoffCriteria(BackoffPolicy.LINEAR,1,TimeUnit.SECONDS)
                .build()
            Log.i(TAG, "点击按钮  启动了吗？")
            WorkManager.getInstance(this).enqueue(request)
            Log.i(TAG, "点击按钮  启动了")


            WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.id)
                .observe(this) { workInfo ->
                    when (workInfo.state) {
                        WorkInfo.State.BLOCKED -> {
                            Log.d(TAG, "Work Info. State. BLOCKED")
                        }
                        WorkInfo.State.RUNNING -> {
                            Log.d(TAG, "Work Info. State. RUNNING")
                        }
                        WorkInfo.State.CANCELLED -> {
                            Log.d(TAG, "Work Info. State. CANCELLED")
                        }
                        WorkInfo.State.FAILED -> {
                            Log.d(TAG, "Work Info. State. FAILED")
                        }
                        WorkInfo.State.ENQUEUED -> {
                            Log.d(TAG, "Work Info. State. ENQUEUED")
                        }
                        WorkInfo.State.SUCCEEDED -> {
                            Log.d(TAG, "Work Info. State. SUCCEEDED")
                        }
                        else -> {

                        }
                    }
                }

        }

        binding.btnCancel.setOnClickListener{
            WorkManager.getInstance(this).cancelAllWorkByTag("qaq")
        }

    }

}